package com.mt.controller;

import cn.hutool.extra.ssh.JschUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.mt.constants.Result;
import com.mt.enums.Status;
import com.mt.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author Wang
 * @Description 文件上传服务
 * @date 2021/1/28-16:23
 */
@RestController
@Slf4j
public class uploadController {
    private static String serverHost = "119.29.181.69";
    private static int port = 22;



    @PostMapping("/upload")
    public Result<String> uploadImage(@RequestParam("file")MultipartFile file) {
        log.info(file.isEmpty()+"  and  " +file.getOriginalFilename());
        Session session = null;
        ChannelSftp channelSftp = null;
        Result<String> res = new Result<>();
        if (file.isEmpty()) {
            throw new GlobalException(Status.FILE_IS_NULL_ERROR);
        }
        String fileName = file.getOriginalFilename();
        try {
            session = JschUtil.getSession(serverHost, port, "root", "WANGjing13");
//            channelSftp = (ChannelSftp) session.openChannel("sftp");
//            channelSftp.connect();
            channelSftp = JschUtil.openSftp(session);
            channelSftp.put(file.getInputStream(), "/mt/img/" + fileName);
        }catch (SftpException e) {
            log.error(e.toString());
           throw new GlobalException(Status.ERROR);
        } catch (IOException e) {
            log.error(e.toString());
            throw new GlobalException(Status.UPLOAD_ERROR);
        }catch (Exception e){
            log.error(e.toString());
        }finally {
            JschUtil.close(session);
            JschUtil.close(channelSftp);

        }
        res.success(fileName);
        return res;
    }
}
